package com.kly.springbootinit.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kly.springbootinit.annotation.AuthCheck;
import com.kly.springbootinit.common.BaseResponse;
import com.kly.springbootinit.common.DeleteRequest;
import com.kly.springbootinit.common.ErrorCode;
import com.kly.springbootinit.common.ResultUtils;
import com.kly.springbootinit.constant.UserConstant;
import com.kly.springbootinit.exception.BusinessException;
import com.kly.springbootinit.exception.ThrowUtils;
import com.kly.springbootinit.model.dto.vehicle.*;
import com.kly.springbootinit.model.entity.User;
import com.kly.springbootinit.model.entity.Vehicle;
import com.kly.springbootinit.model.vo.VehicleVO;
import com.kly.springbootinit.service.UserService;
import com.kly.springbootinit.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 车辆管理接口
 *
 * @author <a href="https://github.com/likly">程序员鹿七</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/vehicle")
@Slf4j
public class VehicleController {

    @Resource
    private VehicleService vehicleService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建车辆管理
     *
     * @param vehicleAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addVehicle(@RequestBody VehicleAddRequest vehicleAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(vehicleAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleAddRequest, vehicle);
        // 数据校验
        vehicleService.validVehicle(vehicle, true);
        // 写入数据库
        boolean result = vehicleService.save(vehicle);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newVehicleId = vehicle.getId();
        return ResultUtils.success(newVehicleId);
    }

    /**
     * 删除车辆管理
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteVehicle(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Vehicle oldVehicle = vehicleService.getById(id);
        ThrowUtils.throwIf(oldVehicle == null, ErrorCode.NOT_FOUND_ERROR);

        // 操作数据库
        boolean result = vehicleService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新车辆管理（仅管理员可用）
     *
     * @param vehicleUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateVehicle(@RequestBody VehicleUpdateRequest vehicleUpdateRequest) {
        if (vehicleUpdateRequest == null || vehicleUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleUpdateRequest, vehicle);
        // 数据校验
        vehicleService.validVehicle(vehicle, false);
        // 判断是否存在
        long id = vehicleUpdateRequest.getId();
        Vehicle oldVehicle = vehicleService.getById(id);
        ThrowUtils.throwIf(oldVehicle == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = vehicleService.updateById(vehicle);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取车辆管理（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<VehicleVO> getVehicleVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Vehicle vehicle = vehicleService.getById(id);
        ThrowUtils.throwIf(vehicle == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(vehicleService.getVehicleVO(vehicle, request));
    }

    /**
     * 分页获取车辆管理列表（仅管理员可用）
     *
     * @param vehicleQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Vehicle>> listVehicleByPage(@RequestBody VehicleQueryRequest vehicleQueryRequest) {
        long current = vehicleQueryRequest.getCurrent();
        long size = vehicleQueryRequest.getPageSize();
        // 查询数据库
        Page<Vehicle> vehiclePage = vehicleService.page(new Page<>(current, size),
                vehicleService.getQueryWrapper(vehicleQueryRequest));
        return ResultUtils.success(vehiclePage);
    }

    /**
     * 分页获取车辆管理列表（封装类）
     *
     * @param vehicleQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<VehicleVO>> listVehicleVOByPage(@RequestBody VehicleQueryRequest vehicleQueryRequest,
                                                             HttpServletRequest request) {
        long current = vehicleQueryRequest.getCurrent();
        long size = vehicleQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Vehicle> vehiclePage = vehicleService.page(new Page<>(current, size),
                vehicleService.getQueryWrapper(vehicleQueryRequest));
        // 获取封装类
        return ResultUtils.success(vehicleService.getVehicleVOPage(vehiclePage, request));
    }

    /**
     * 分页获取当前登录用户创建的车辆管理列表
     *
     * @param vehicleQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<VehicleVO>> listMyVehicleVOByPage(@RequestBody VehicleQueryRequest vehicleQueryRequest,
                                                               HttpServletRequest request) {
        ThrowUtils.throwIf(vehicleQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        long current = vehicleQueryRequest.getCurrent();
        long size = vehicleQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Vehicle> vehiclePage = vehicleService.page(new Page<>(current, size),
                vehicleService.getQueryWrapper(vehicleQueryRequest));
        // 获取封装类
        return ResultUtils.success(vehicleService.getVehicleVOPage(vehiclePage, request));
    }

    /**
     * 编辑车辆管理（给用户使用）
     *
     * @param vehicleEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editVehicle(@RequestBody VehicleEditRequest vehicleEditRequest, HttpServletRequest request) {
        if (vehicleEditRequest == null || vehicleEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(vehicleEditRequest, vehicle);
        // 数据校验
        vehicleService.validVehicle(vehicle, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = vehicleEditRequest.getId();
        Vehicle oldVehicle = vehicleService.getById(id);
        ThrowUtils.throwIf(oldVehicle == null, ErrorCode.NOT_FOUND_ERROR);

        // 操作数据库
        boolean result = vehicleService.updateById(vehicle);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion





}
